package com.fruit.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fruit.common.CookieUtil;
import com.fruit.constants.RedisConstant;
import com.fruit.service.redis.UserRedisUtil;

/**
 * WapRedisSecurityInterceptor
 *
 * @author Administrator
 * @version 2017.11.30 12:20
 */
@Slf4j
public class WapRedisSecurityInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserRedisUtil userRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        String userToken = CookieUtil.getValue(request, "WAP_USER_TOOKEN");
        String tokenValue = "";
        Integer userId = null;
        if (StringUtils.isNotEmpty(userToken)) {
            if (userRedisService.isExists(RedisConstant.WAP_USER_TOOKEN + userToken)) {
                userRedisService.setUserTokenExpire(RedisConstant.WAP_USER_TOOKEN + userToken);
                tokenValue = userRedisService.getUserToken(RedisConstant.WAP_USER_TOOKEN + userToken);
            } else {
                log.info("redis中不存在用户token [{}]", userToken);
            }
        }
        String[] tokenValues = StringUtils.split(tokenValue, "_");
        if (tokenValues != null && tokenValues.length != 0) {
            userId = Integer.parseInt(tokenValues[0]);
        }
        if (userId != null) {
            log.info("从redis获取到了用户{}的信息", userId);
            request.getSession().setAttribute("userId", userId);
        } else {
            log.info("没有从redis中获取到用户的信息");
            request.getSession().removeAttribute("userId");
        }

        return true;
    }
}
